import dynamic from 'next/dynamic'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import Seo from '../../../core/components/Seo'
import Promocrumb from '../../../lib/promo/components/Promocrumb'
import { fetchPromoItemsSolr } from '../../../api/promoApi'
import LogoSpinner from '../../../core/components/elements/Spinner/LogoSpinner.jsx'
import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card'
import { IPromotion } from '../../../../src-migrate/types/promotion'
import React from 'react'
import { SolrResponse } from "../../../../src-migrate/types/solr.ts";


const BasicLayout = dynamic(() => import('../../../core/components/layouts/BasicLayout'))

export default function PromoDetail() {
  const router = useRouter()
  const { slug = '' } = router.query
  const [promoItems, setPromoItems] = useState<any[]>([])
  const [promoData, setPromoData] = useState<IPromotion[] | null>(null)
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 12; // Jumlah item yang ingin ditampilkan per halaman
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = Math.min(startIndex + itemsPerPage, promoData?.length || 0);
  const visiblePromotions = promoData?.slice(startIndex, endIndex);
  const [loading, setLoading] = useState(true); // Menambahkan status loading


  useEffect(() => {
    const loadPromo = async () => {
      try {
        const items = await fetchPromoItemsSolr(Array.isArray(slug) ? slug[0] : slug)
        console.log("slug sekarang ", slug)
        
        setPromoItems(items)
        console.log("data dari promotion pakai SOLR", items)

        if (items.length === 0) {
          setPromoData([])
          setLoading(false);
          return;
        }

        const promoDataPromises = items.map(async (item) => {
          const queryParams = new URLSearchParams({ q: `id:${item.id}` })
          console.log("Constructed URL:", `/solr/promotion_program_lines/select?${queryParams.toString()}`)

          try {
            const response = await fetch(`/solr/promotion_program_lines/select?${queryParams.toString()}`)
            console.log("respon data ", response)
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`)
            }

            const data: SolrResponse<any[]> = await response.json()
            console.log("data promo IPromotion[]", data)
            
            const promotions = await map(data.response.docs)
            return promotions;
          } catch (fetchError) {
            console.error("Error fetching promotion data:", fetchError)
            return [];
          }
        });

        const promoDataArray = await Promise.all(promoDataPromises);
        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        setPromoData(mergedPromoData);
        setTimeout(() => setLoading(false), 120); // Menambahkan delay 200ms sebelum mengubah status loading
      } catch (loadError) {
        console.error("Error loading promo items:", loadError)
        setLoading(false);
      }
    }

    if (slug) {
      loadPromo()
    }
  }, [slug])

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'auto' }); // Auto scroll to top when component mounts or updates
  }, []); // Run only once when component mounts
  

  const map = async (promotions: any[]): Promise<IPromotion[]> => {
    const result: IPromotion[] = []
  
    for (const promotion of promotions) {
      const data: IPromotion = {
        id: promotion.id,
        program_id: promotion.program_id_i,
        name: promotion.name_s,
        type: {
          value: promotion.type_value_s,
          label: promotion.type_label_s,
        },
        limit: promotion.package_limit_i,
        limit_user: promotion.package_limit_user_i,
        limit_trx: promotion.package_limit_trx_i,
        price: promotion.price_f,
        total_qty: promotion.total_qty_i,
        products: JSON.parse(promotion.products_s),
        free_products: JSON.parse(promotion.free_products_s),
      }
  
      result.push(data)
    }
  
    return result
  }

  console.log("data yg dikirim ke ProductPromoCard", promoData)
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  const goToNextPage = () => {
    setCurrentPage((prevPage) => prevPage + 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  
  const goToPreviousPage = () => {
    setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  
  return (
    <BasicLayout>
      <Seo
        title={`Promo ${Array.isArray(slug) ? slug[0] : slug} Terkini`} 
        description='B2B Marketplace MRO & Industri dengan Layanan Pembayaran Tempo, Faktur Pajak, Online Quotation, Garansi Resmi & Harga Kompetitif'
      />
      <Promocrumb brandName={capitalizeFirstLetter(Array.isArray(slug) ? slug[0] : slug)} /> 

      {loading ? (
        <div className='container flex justify-center my-4'>
        <LogoSpinner width={48} height={48} />
      </div>
      ) : promoData && promoItems.length >= 1 ? (
        <>
          <div className='flex flex-wrap justify-center'>
            {visiblePromotions?.map((promotion) => (
              <div key={promotion.id} className="min-w-[40px] max-w-[400px] mr-[20px] mb-[20px] sm:w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
                <ProductPromoCard promotion={promotion} slug={Array.isArray(slug) ? slug[0] : slug} />
              </div>
            ))}
          </div>
          <div className="flex justify-center mt-4">
            <button onClick={goToPreviousPage} disabled={currentPage === 1} className="mr-2 px-4 py-2 bg-gray-200 rounded">Back</button>
            <button onClick={goToNextPage} disabled={endIndex >= promoData.length} className="px-4 py-2 bg-gray-200 rounded">Next</button>
          </div>
        </>
      ) : (
        <div className="text-center my-8">
          <p>Belum ada promo pada kategori ini</p>
        </div>
      )}
    </BasicLayout>
  )
}